package com.sk.weichat.ui.message.search;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.sk.weichat.AppConstant;
import com.sk.weichat.R;
import com.sk.weichat.adapter.SearchChatRecodeAdapter;
import com.sk.weichat.adapter.SearchContactAdapter;
import com.sk.weichat.adapter.SearchGroupRecodeAdapter;
import com.sk.weichat.bean.Friend;
import com.sk.weichat.db.dao.ChatMessageDao;
import com.sk.weichat.db.dao.FriendDao;
import com.sk.weichat.ui.base.EditBaseActivity;
import com.sk.weichat.ui.me.PersonalCenterActivity;
import com.sk.weichat.ui.message.ChatActivity;
import com.sk.weichat.ui.message.MucChatActivity;
import com.sk.weichat.util.Constants;
import com.sk.weichat.util.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

/**
 * 搜索
 */
public class SearchActivity extends EditBaseActivity implements View.OnClickListener {

    private LinearLayout ll_layout_search_empty;
    private EditText et_search_user;
    private ImageView iv_clear_user;
    private TextView tv_finish_search_user;
    private LinearLayout ll_search_select_btn;
    private LinearLayout linear_search_tip;
    private TextView tv_search_text;

    private TextView tv_search_contact;
    private TextView tv_search_chat_recode;

    //好友
    private LinearLayout ll_friends;
    private RecyclerView recy_friends;
    private TextView tv_more_friends;
    private String mLoginUserId;
    private List<Friend> mFriendList = new ArrayList<>();//好友列表
    private SearchContactAdapter mAdapter;

    //聊天记录
    private LinearLayout ll_chat_record;
    private RecyclerView recy_chat_record;
    private TextView tv_more_chat_record;
    private List<Friend> mChatRecordList = new ArrayList<>();//聊天记录列表
    private SearchChatRecodeAdapter mChatRecordAdapter;

    //群聊记录
    private LinearLayout ll_group_chat;
    private RecyclerView recy_img_group_chat;
    private TextView tv_more_group_chat;
    private List<Friend> mRoomsChatList = new ArrayList<>();//群聊记录列表
    private SearchGroupRecodeAdapter mRoomsChatAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        getSupportActionBar().hide();
        mLoginUserId = coreManager.getSelf().getUserId();
        initView();
        initFriendsView();
        initChatRecodeView();
        initRoomsChatRecodeView();
        //弹出键盘输入
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    private void initView() {

        ll_layout_search_empty = findViewById(R.id.ll_layout_search_empty);
        et_search_user = findViewById(R.id.et_search_user);
        iv_clear_user = findViewById(R.id.iv_clear_user);
        tv_finish_search_user = findViewById(R.id.tv_finish_search_user);
        linear_search_tip = findViewById(R.id.linear_search_tip);
        tv_search_text = findViewById(R.id.tv_search_text);
        ll_search_select_btn = findViewById(R.id.ll_search_select_btn);
        tv_search_contact = findViewById(R.id.tv_search_contact);
        tv_search_chat_recode = findViewById(R.id.tv_search_chat_recode);

        linear_search_tip.setOnClickListener(this);
        tv_search_contact.setOnClickListener(this);
        tv_search_chat_recode.setOnClickListener(this);
        iv_clear_user.setOnClickListener(this);
        tv_finish_search_user.setOnClickListener(this);
        et_search_user.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s == null || s.length() == 0) {
                    iv_clear_user.setVisibility(View.INVISIBLE);
                    ll_search_select_btn.setVisibility(View.VISIBLE);
                    linear_search_tip.setVisibility(View.GONE);
                    ll_layout_search_empty.setVisibility(View.GONE);
                    //清除好友列表
                    mFriendList.clear();
                    mAdapter.notifyDataSetChanged();
                    ll_friends.setVisibility(View.GONE);
                    //清除聊天记录列表
                    mChatRecordList.clear();
                    mChatRecordAdapter.notifyDataSetChanged();
                    ll_chat_record.setVisibility(View.GONE);
                    //清除群聊
                    mRoomsChatList.clear();
                    mRoomsChatAdapter.notifyDataSetChanged();
                    ll_group_chat.setVisibility(View.GONE);
                    return;
                }
                iv_clear_user.setVisibility(View.VISIBLE);
                linear_search_tip.setVisibility(View.VISIBLE);
                String tipStr = "网络查找“<font color='#8d76fe'>" + s + "</font>”相关的人和群";
                tv_search_text.setText(Html.fromHtml(tipStr));
                ll_search_select_btn.setVisibility(View.GONE);
                //传递关键字  改变字体颜色
                mAdapter.setKeyword(s.toString());
                mChatRecordAdapter.setKeyword(s.toString());
                mRoomsChatAdapter.setKeyword(s.toString());
                SearchContact();
                SearchChatRecode();
                SearchRoomsChatRecode();

                if (mFriendList.size() == 0 && mChatRecordList.size() == 0 && mRoomsChatList.size() == 0) {
                    ll_layout_search_empty.setVisibility(View.VISIBLE);
                } else {
                    ll_layout_search_empty.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        et_search_user.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    if (TextUtils.isEmpty(et_search_user.getText().toString())) {
                        ToastUtil.showToast(SearchActivity.this, "请输入搜索内容");
                        return true;
                    }
                    SearchContact();
                    SearchChatRecode();
                    SearchRoomsChatRecode();
                    if (mFriendList.size() == 0 && mChatRecordList.size() == 0 && mChatRecordList.size() == 0) {
                        ll_layout_search_empty.setVisibility(View.VISIBLE);
                    } else {
                        ll_layout_search_empty.setVisibility(View.GONE);
                    }
                    return true;
                }
                return false;
            }
        });
    }

    /**
     * 初始化好友列表
     */
    private void initFriendsView() {
        //好友
        ll_friends = findViewById(R.id.ll_friends);
        recy_friends = findViewById(R.id.recy_friends);
        tv_more_friends = findViewById(R.id.tv_more_friends);
        tv_more_friends.setOnClickListener(this);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recy_friends.setLayoutManager(manager);
        mAdapter = new SearchContactAdapter(mFriendList);
        mAdapter.setHasStableIds(true);
        recy_friends.setNestedScrollingEnabled(true);
        recy_friends.setAdapter(mAdapter);
        //禁止RecyclerView的默认动画
        ((SimpleItemAnimator) recy_friends.getItemAnimator()).setSupportsChangeAnimations(false);
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                Friend friend = mFriendList.get(position);

                if (view.getId() == R.id.img_search_avatar) {
                    Intent intent = new Intent(SearchActivity.this, PersonalCenterActivity.class);
                    intent.putExtra(AppConstant.EXTRA_USER_ID, friend.getUserId());
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(SearchActivity.this, ChatActivity.class);
                    intent.putExtra(ChatActivity.FRIEND, friend);
                    intent.putExtra(Constants.NEW_MSG_NUMBER, friend.getUnReadNum());
                    startActivity(intent);

                }

            }
        });
    }

    /**
     * 初始化 聊天记录
     */
    private void initChatRecodeView() {
        //聊天记录
        ll_chat_record = findViewById(R.id.ll_chat_record);
        recy_chat_record = findViewById(R.id.recy_chat_record);
        tv_more_chat_record = findViewById(R.id.tv_more_chat_record);
        tv_more_chat_record.setOnClickListener(this);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recy_chat_record.setLayoutManager(manager);
        mChatRecordAdapter = new SearchChatRecodeAdapter(mChatRecordList, true);
        mChatRecordAdapter.setHasStableIds(true);
        recy_chat_record.setNestedScrollingEnabled(true);
        recy_chat_record.setAdapter(mChatRecordAdapter);
        //禁止RecyclerView的默认动画
        ((SimpleItemAnimator) recy_chat_record.getItemAnimator()).setSupportsChangeAnimations(false);
        mChatRecordAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                Friend friend = mChatRecordList.get(position);
                Intent intent;
                if (friend.getContextNum() > 1) {//判断是否有多条记录
                    intent = new Intent(SearchActivity.this, MoreChatRecordActivity.class);
                    intent.putExtra(ChatActivity.FRIEND, friend);
                    intent.putExtra("content", et_search_user.getText().toString());
                } else {
                    if (friend.getRoomFlag() == 0) {//单聊
                        intent = new Intent(SearchActivity.this, ChatActivity.class);
                        intent.putExtra(ChatActivity.FRIEND, friend);
                    } else {//群聊
                        intent = new Intent(SearchActivity.this, MucChatActivity.class);
                        intent.putExtra(AppConstant.EXTRA_USER_ID, friend.getUserId());
                        intent.putExtra(AppConstant.EXTRA_NICK_NAME, friend.getNickName());
                    }
                    intent.putExtra("isserch", true);
                    intent.putExtra("jilu_id", friend.getChatRecordTimeOut());
                }
                startActivity(intent);
            }
        });
    }

    /**
     * 初始化 群聊记录
     */
    private void initRoomsChatRecodeView() {
        ll_group_chat = findViewById(R.id.ll_group_chat);
        recy_img_group_chat = findViewById(R.id.recy_img_group_chat);
        tv_more_group_chat = findViewById(R.id.tv_more_group_chat);
        tv_more_group_chat.setOnClickListener(this);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recy_img_group_chat.setLayoutManager(manager);

        mRoomsChatAdapter = new SearchGroupRecodeAdapter(mRoomsChatList);
        mRoomsChatAdapter.setHasStableIds(true);
        recy_img_group_chat.setNestedScrollingEnabled(true);
        recy_img_group_chat.setAdapter(mRoomsChatAdapter);
        //禁止RecyclerView的默认动画
        ((SimpleItemAnimator) recy_img_group_chat.getItemAnimator()).setSupportsChangeAnimations(false);

        mRoomsChatAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                Friend friend = mRoomsChatList.get(position);
                Intent intent = new Intent(SearchActivity.this, MucChatActivity.class);
                intent.putExtra(AppConstant.EXTRA_USER_ID, friend.getUserId());
                intent.putExtra(AppConstant.EXTRA_NICK_NAME, friend.getNickName());
                intent.putExtra(AppConstant.EXTRA_IS_GROUP_CHAT, true);
                startActivity(intent);
            }
        });
    }


    @Override
    public void onClick(View v) {

        if (v == tv_finish_search_user) {
            finish();
        } else if (v == iv_clear_user) {
            et_search_user.setText("");
        } else if (v == tv_search_contact) {
            startActivity(new Intent(this, SearchContactActivity.class));
        } else if (v == tv_search_chat_recode) {
            startActivity(new Intent(this, SearchChatRecordActivity.class));
        } else if (v == linear_search_tip) {//搜索用户和群
            startActivity(new Intent(this, SearchUserAndRoomActivity.class).putExtra("search_user", et_search_user.getText().toString()));
        } else if (v == tv_more_friends) {//更多联系人
            startActivity(new Intent(this, SearchContactActivity.class).putExtra("search_more", et_search_user.getText().toString()));
        } else if (v == tv_more_chat_record) {//更多聊天记录
            startActivity(new Intent(this, SearchChatRecordActivity.class).putExtra("search_more", et_search_user.getText().toString()));
        } else if (v == tv_more_group_chat) {
            startActivity(new Intent(this, SearchGroupChatActivity.class).putExtra("search_more", et_search_user.getText().toString()));
        }
    }

    /**
     * 搜索联系人
     */
    private void SearchContact() {
        List<Friend> datas = FriendDao.getInstance().QuearyFriends(mLoginUserId, et_search_user.getText().toString());//查找好友和关注 列表
        if (datas != null && datas.size() > 0) {
            if (datas.size() > 3) {
                tv_more_friends.setVisibility(View.VISIBLE);
            } else {
                tv_more_friends.setVisibility(View.GONE);
            }
            if (mFriendList.size() > 0) {
                mFriendList.clear();
            }
            for (Friend friend : datas) {
                if (mFriendList.size() < 3) {//显示三条
                    mFriendList.add(friend);
                }
            }
            if (mFriendList.size() > 0) {
                ll_friends.setVisibility(View.VISIBLE);
            } else {
                ll_friends.setVisibility(View.GONE);
            }
            mAdapter.notifyDataSetChanged();
        } else {
            if (mFriendList.size() > 0) {
                mFriendList.clear();
                mAdapter.notifyDataSetChanged();
            }
            ll_friends.setVisibility(View.GONE);
        }
    }

    /**
     * 搜索聊天记录
     */
    private void SearchChatRecode() {
        List<Friend> chat_datas = ChatMessageDao.getInstance().queryAllChatMessageByContent(mLoginUserId, et_search_user.getText().toString());//查找聊天记录
        if (chat_datas != null && chat_datas.size() > 0) {
            if (chat_datas.size() > 3) {
                tv_more_chat_record.setVisibility(View.VISIBLE);
            } else {
                tv_more_chat_record.setVisibility(View.GONE);
            }
            if (mChatRecordList.size() > 0) {
                mChatRecordList.clear();
            }
            for (Friend friend : chat_datas) {
                if (mChatRecordList.size() < 3) {//显示三条
                    mChatRecordList.add(friend);
                }
            }
            mChatRecordAdapter.notifyDataSetChanged();
            ll_chat_record.setVisibility(View.VISIBLE);
        } else {
            if (mChatRecordList.size() > 0) {
                mChatRecordList.clear();
                mChatRecordAdapter.notifyDataSetChanged();
            }
            ll_chat_record.setVisibility(View.GONE);
        }
    }


    /**
     * 查找群聊记录
     */
    private void SearchRoomsChatRecode() {
        List<Friend> rooms_datas = FriendDao.getInstance().getRoomsByNickName(mLoginUserId, et_search_user.getText().toString());//查找群聊
        if (rooms_datas != null && rooms_datas.size() > 0) {
            if (rooms_datas.size() > 3) {
                tv_more_group_chat.setVisibility(View.VISIBLE);
            } else {
                tv_more_group_chat.setVisibility(View.GONE);
            }
            if (mRoomsChatList.size() > 0) {
                mRoomsChatList.clear();
            }
            for (Friend friend : rooms_datas) {
                if (mRoomsChatList.size() < 3) {//显示三条
                    mRoomsChatList.add(friend);
                }
            }
            mRoomsChatAdapter.notifyDataSetChanged();
            ll_group_chat.setVisibility(View.VISIBLE);
        } else {
            if (mRoomsChatList.size() > 0) {
                mRoomsChatList.clear();
                mRoomsChatAdapter.notifyDataSetChanged();
            }
            ll_group_chat.setVisibility(View.GONE);
        }
    }


    @Subscribe(threadMode = ThreadMode.MainThread)
    public void helloEventBus(String cancle) {
        if (cancle.equals("cancle")) {
            finish();
        }
    }
}
